package com.akbar.security;

import com.akbar.utils.ResponseUtil;
import com.akbar.utils.ResultUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {

        log.error("权限不足 {}", accessDeniedException.getMessage());

        ResponseUtil.writeJson(
                response,
                HttpServletResponse.SC_UNAUTHORIZED, // 401
                ResultUtil.error(403, "Forbidden: " + accessDeniedException.getMessage())
        );
    }
}
